<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="新增元素"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="元素类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择">
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="根据图片自动计算大小"
            prop="auto_size"
            label-width="130"
          >
            <el-switch v-model="form.auto_size"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="页面宽度" prop="width">
            <el-input-number v-model.number="form.width" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="页面高度" prop="height">
            <el-input-number v-model.number="form.height" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="距左" prop="left">
            <el-input-number v-model.number="form.left" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="距顶" prop="top">
            <el-input-number v-model.number="form.top" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="图片" prop="link_image">
        <img-upload
          :path="imgPath"
          :base-api="baseApi"
          :src="form.link_image ? baseUrl + form.link_image : ''"
          @update="handleUpdate"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import findLast from 'lodash/findLast'
  import ImgUpload from '@/components/ImgUpload'
  import mixin from '@/views/editor/mixin.js'
  import {
    types,
    buttonForm,
    imageForm,
    videoForm,
  } from '@/views/editor/config'
  import pictureSvg from '@/assets/imgs/picture.svg'
  import imageSvg from '@/assets/imgs/image.svg'
  import mediaSvg from '@/assets/imgs/media.svg'

  export default {
    name: 'ElementAdd',
    components: {
      ImgUpload,
    },
    mixins: [mixin],
    data() {
      // var checkType = (rule, value, callback) => {
      //   if (!value) {
      //     return callback(new Error('年龄不能为空'));
      //   }
      //   setTimeout(() => {
      //     if (!Number.isInteger(value)) {
      //       callback(new Error('请输入数字值'));
      //     } else {
      //       if (value < 18) {
      //         callback(new Error('必须年满18岁'));
      //       } else {
      //         callback();
      //       }
      //     }
      //   }, 1000);
      // };
      return {
        root: {},
        types,
        form: {
          id: '',
          type: 'button',
          auto_size: true,
          left: 0,
          top: 0,
          width: 200,
          height: 200,
          link_image: '',
        },
        rules: {
          type: [
            { required: true, trigger: 'blur', message: '请选择元素类型' },
          ],
        },
        dialogFormVisible: false,
      }
    },
    computed: {
      baseApi() {
        return this.root.baseApi
      },
      baseUrl() {
        return this.root.baseUrl
      },
      imgPath() {
        return `topic/${this.root.topicKey}`
      },
      doms() {
        return this.root.doms
      },
    },
    created() {},
    methods: {
      handleUpdate(url) {
        this.form.link_image = url
        if (this.form.auto_size) {
          const img = new Image()
          img.onload = () => {
            this.$set(this.form, 'width', img.width)
            this.$set(this.form, 'height', img.height)
          }
          img.src = `${this.baseUrl}${url}`
        }
      },
      showEdit() {
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      addButton() {
        const form = Object.assign({}, buttonForm, this.form)
        !form.link_image && (form._link_image = pictureSvg)
        const buttons = this.doms.filter((item) => item.type === 'button')
        const lastButton = buttons[buttons.length - 1]
        if (lastButton) {
          const id = lastButton.id
          let idStr = id.split('_').pop()
          if (isNaN(idStr * 1)) {
            idStr =
              buttons.length === 1
                ? 0
                : buttons[buttons.length - 2].id.split('_').pop()
          }
          form.id = 'focus_card_' + (idStr * 1 + 1)
        } else {
          form.id = 'focus_card_1'
        }
        this.root.addDom(form)
      },
      addImage() {
        const form = Object.assign({}, imageForm, this.form)
        !form.link_image && (form._link_image = imageSvg)
        this.root.addDom(form)
      },
      addVideo() {
        const form = Object.assign({}, videoForm, this.form)
        !form.link_image && (form._link_image = mediaSvg)
        this.root.addDom(form)
      },
      save() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            switch (this.form.type) {
              case 'button':
                this.addButton()
                break
              case 'image':
                this.addImage()
                break
              case 'video':
                this.addVideo()
                break
            }
            this.$baseMessage('元素添加成功', 'success')
            this.close()
          }
        })
      },
    },
  }
</script>
